<template>
  <div class="h100 oh rel" ref="map" id="group-map"></div>
</template>
<script>
import { initViewer } from "@/public/lib/map";
import { Cesium, wutu3d } from "@/public/global/const";
import { staticComputer } from "@/public/util/vue";
import CesiumEvent from "@/public/class/CesiumEvent";
import { FetchGetTailingLocation } from "@/api";

// Cesium.ScreenSpaceEventTypeExtend = {
//   MOUSE_ENTER: "MOUSE_ENTER",
//   MOUSE_LEAVE: "MOUSE_LEAVE",
// };
export default {
  name: "TheCesiumMap",
  components: {},
  props: {
    value:Number
  },
  data() {
    return {};
  },
  computed: {
    cesiumMap: staticComputer({}),
    waveDatasource: staticComputer({}),
  },
  watch:{
    value:'$_focusToPnd'
  },
  mounted() {
    const viewer = initViewer(this.$refs.map, false, {
      disableZoom: true,
      center:{
        "y": 21.263107,
        "x": 117.41503,
        "z": 870334.33,
        "heading": 0.3,
        "pitch": -54.9,
        "roll": 359.4
      },
    });
    viewer.imageryLayers.get(0).gamma = 0.8;
    viewer.wutu.openFlyAnimation(() => {});
    this.cesiumMap = {
      viewer,
    };

    this.$_billboardManege();

    this.$emit("renderMap", this.cesiumMap);
  },
  created() {
    window.closeDangerLabel = () => {
      if (this.label) {
        this.label.visible = false;
      }
    };
  },
  methods: {
    /**
     * 聚焦某个矿
     */
    $_focusToPnd() {
      if(!this.value){
        return
      }
      const obj = this.waveDatasource.entities.getById(this.value)
      if(!obj){
        return
      }
      this.cesiumMap.viewer.selectedEntity = obj

      let props = obj.feature.properties;
      let coordinates = obj.feature.geometry.coordinates;
      let level =
          ["一", "二", "三", "四", "五", "六", "七", "八", "九"][
          props.level - 1
              ] || "一";
      const pos = obj.feature.geometry.coordinates;

      const position = Cesium.Cartesian3.fromDegrees(pos[0], pos[1])
      const currentCameraView = this.cesiumMap.viewer.wutu.getCameraView()
      this.cesiumMap.viewer.wutu.centerPoint(
          position,
          {
            radius:currentCameraView.z,
            duration: 2,
            ...currentCameraView
          })


      const content = `
                            <table>
                                <tr><td>区域：</td><td>${props.areaName}</td></tr>
                                <tr><td>尾矿库：</td><td>${props.tailingName}</td></tr>
                                <tr><td>经纬度：</td><td>${coordinates[1]}N, ${coordinates[0]}E</td></tr>
                                <tr><td>等级：</td><td>${level}等</td></tr>
                            </table>
                        `;
      this.$_addLabel(position, "尾矿信息", content);
      // window.open(
      //     location.origin +
      //         this.$router.resolve({
      //             name: "Client",
      //         }).href,
      //     "_blank",
      // );
    },
    $_billboardManege() {
      this.waveDatasource = new Cesium.CustomDataSource("ds_effect");
      this.cesiumMap.viewer.dataSources.add(this.waveDatasource);
      const alarmIdx = -1;
      const eventHandler = new CesiumEvent({ viewer: this.cesiumMap.viewer });
      FetchGetTailingLocation().then((tailingLocations) => {
        const poiData = {
          type: "FeatureCollection",
          features: tailingLocations.map((tailingLocation) => {
            return {
              geometry: {
                coordinates: [
                  tailingLocation.longitude,
                  tailingLocation.latitude,
                ],
              },
              properties: {
                level: tailingLocation.levelId,
                areaName: tailingLocation.areaName,
                tailingName: tailingLocation.tailingName,
                platformCode: tailingLocation.platformCode,
                ...tailingLocation
              },
            };
          }),
        };
        poiData.features.forEach((feature, index) => {
          const pos = feature.geometry.coordinates;
          const position = Cesium.Cartesian3.fromDegrees(pos[0], pos[1]);
          const obj =  this.waveDatasource.entities.add({
            position: position,
            id: feature.properties.tailingPondId,
            billboard:{
              image: process.env.BASE_URL + "images/mount.png",
              position: Cesium.Cartesian3.fromDegrees(pos[0], pos[1]),
              width: 64,
              height: 64,
              color: Cesium.Color.fromCssColorString(
                  alarmIdx === index ? "#FF0000" : "#00FFFF"
              ),
              show: true,
            },
            ellipse: {
              height: 0.0,
              semiMinorAxis: 12000.0 * 2,
              semiMajorAxis: 12000.0 * 2,
              material: new wutu3d.CircleWaveMaterial({
                duration: 6000,
                color:
                  alarmIdx === index
                    ? Cesium.Color.fromCssColorString("rgba(255, 0,0,.2)")
                    : Cesium.Color.AQUA,
                gradient: 0.5,
                count: 2,
              }),
            },
            show: true,
          });
          obj.feature = feature;
          this.cesiumMap.waveDatasource = this.waveDatasource;
          eventHandler.addListen(
            Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
            obj,
            () => {
              if (!feature.properties.platformCode) {
                return;
              }
              window.open(
                `${AppGlobalConfig.FRONT_URL}/${feature.properties.platformCode}`
              );
            }
          );

          eventHandler.addListen(
            Cesium.ScreenSpaceEventType.LEFT_CLICK,
            obj,
            (event) => {
              if (!obj || !obj.feature) return;
              this.$emit('input',obj.feature.properties.tailingPondId)
            }
          );
        });
      });
    },
    $_addLabel(position, title, content, className) {
      const viewer = this.cesiumMap.viewer;
      if (!viewer || !title || !content || !position) return;
      if (this.label) {
        this.label.destroy();
      }
      this.label = new wutu3d.DivPoint(viewer, {
        html: `<div  class="divpoint2 ${
          className || ""
        }" style="display:none;width: 400px;height: 160px;">
                    <div class="title" style="top:10px;left:120px;">${title}</div>
                    <div class="title-close" onclick="closeDangerLabel()"></div>
                    <div class="content" style="width: 250px;left: 120px;">${content}</div>
                  </div >`,
        anchor: [0, 120],
        position: position,
        // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(1000, 200000),//按视距距离显示
        // scaleByDistance: new Cesium.NearFarScalar(10000, 1.0, 100000, 0.1),
      });
      this.label.visible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.h100 {
  height: 100%;
}
</style>
